package com.cmccgz.udacs_landlord_webapp.data;

import com.cmccgz.baselibrary.utils.SharedPreferencesUtil;
import com.cmccgz.udacs_landlord_webapp.base.ApiService;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.base.GlobalContext;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.bean.ResultBean;
import com.cmccgz.udacs_landlord_webapp.update.StringUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.util.List;

import rx.Subscriber;

public class DevicesRepository implements DevicesDataSource{
    @Override
    public void getDevices(final OnGetDevicesLisenter callBack) {
        if (callBack==null) {
            return;
        }
        //拿缓存
        List<DeviceInfoBean> deviceList = AppConfig.getDeviceList();
        callBack.getDevicesCache(deviceList);
        ApiService.deviceSync().subscribe(new Subscriber<ResultBean<List<DeviceInfoBean>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                callBack.getDevicesError("获取列表失败！");
            }

            @Override
            public void onNext(ResultBean<List<DeviceInfoBean>> listResultBean) {
                if (listResultBean!=null
                        &&listResultBean.rsmsg!=null
                        &&"0".equals(listResultBean.rsmsg.rscode)
                        &&listResultBean.resp!=null) {
                    callBack.getDevicesSuccess(listResultBean.resp);
                    //存缓存
                    Gson gson = new Gson();
                    String json = gson.toJson(listResultBean.resp);
                    json=json==null?"":json;
                    Logger.json(json);
                    SharedPreferencesUtil.putString(GlobalContext.getInstance(), AppConfig.SP_DEVICES_INFO, json);
                }else{
                    String errorMsg=listResultBean!=null
                            &&listResultBean.rsmsg!=null
                            && !StringUtils.isEmpty(listResultBean.rsmsg.rsdesc)
                            ?listResultBean.rsmsg.rsdesc
                            :"获取列表失败！";
                    callBack.getDevicesError(errorMsg);
                }
            }
        });
    }
}
